package com.dc.toolkit.guava.base;

import com.google.common.base.CharMatcher;
import com.google.common.base.Charsets;
import com.google.common.base.Strings;
import lombok.extern.slf4j.Slf4j;
import org.junit.Test;

import java.nio.charset.Charset;

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.nullValue;
import static org.junit.Assert.assertThat;

/**
 * Description: Guava_Strings测试类
 * @author: gdc
 * @date: 2021/4/17
 * @version 1.0
 */
@Slf4j
public class StringsTest {


    @Test
    public void testStringsMethods(){
        // 空字符串转换为空对象
        assertThat(Strings.emptyToNull(""), nullValue());

        // 空对象转换为空字符串
        assertThat(Strings.nullToEmpty(null), equalTo(""));

        // 断言 公共前缀
        assertThat(Strings.commonPrefix("Hello", "Xit"), equalTo(""));

        // 断言 公共后缀
        assertThat(Strings.commonSuffix("hello", "echo"), equalTo("o"));

        // 将数据重复多次
        assertThat(Strings.repeat("Alex", 3), equalTo("AlexAlexAlex"));

        // 断言数据是否为空字符串
        assertThat(Strings.isNullOrEmpty(null), equalTo(true));

        assertThat(Strings.isNullOrEmpty(""), equalTo(true));

        // 字符串前缀填充
        assertThat(Strings.padStart("Alex", 3, 'H'), equalTo("Alex"));
        assertThat(Strings.padStart("Alex", 5, 'H'), equalTo("HAlex"));

        // 字符串后缀填充
        assertThat(Strings.padEnd("Alex", 5, 'H'), equalTo("AlexH"));
    }

    @Test
    public void testCharsets(){
        Charset charset = Charset.forName("UTF-8");
        assertThat(Charsets.UTF_8, equalTo(charset));
    }

    @Test
    public void testCharMatcher(){
        assertThat(CharMatcher.javaDigit().matches('5'), equalTo(true));
        assertThat(CharMatcher.javaDigit().matches('x'), equalTo(false));

        // 匹配一个字符串中包含多少个字符
        assertThat(CharMatcher.is('A').countIn("AAbbbbAcc"), equalTo(3));

        // 将空格转换为对应字符
        assertThat(CharMatcher.breakingWhitespace().collapseFrom("       hello Guava ", '*'), equalTo("*hello*Guava*"));

        // 去除所有空格
        assertThat(CharMatcher.javaDigit().or(CharMatcher.whitespace()).removeFrom("hello world java guava"), equalTo("helloworldjavaguava"));
    }

}
